﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace Core.Infrastructure.AnimationService
{
    /// <summary>
    /// Responsible for all visibility animations when conducting screens
    /// </summary>
    public class AnimationService : IAnimationService
    {
        #region Properties

        public Storyboard EnterViewVisibilityStoryboard { get; set; }
        public Storyboard LeaveViewVisibilityStoryboard { get; set; }

        #endregion

        #region Constructors

        public AnimationService()
        {
        }

        #endregion

        /// <summary>
        /// Begins animation on UIEelement
        /// </summary>
        /// <param name="uiElement"></param>
        /// <param name="onEnterComplete"></param>
        public void EnterUIElementAnimation(Action onEnterComplete)
        {
            PerformAnimation(onEnterComplete, this.EnterViewVisibilityStoryboard);
        }

        /// <summary>
        /// Ends animation on uiElement
        /// </summary>
        /// <param name="uiElement"></param>
        /// <param name="onLeaveComplete"></param>
        public void LeaveUIElementAnimation(Action onLeaveComplete)
        {
            PerformAnimation(onLeaveComplete, this.LeaveViewVisibilityStoryboard);
        }

        public void PerformAnimation(Action onAnimationComplete, Storyboard storyBoard)
        {
            if (onAnimationComplete == null)
                throw new ArgumentNullException("Action has to be specified.");

            if (storyBoard == null)
            {
                onAnimationComplete();
                return;
            }

            EventHandler handler = null;

            handler = (s, e) =>
               {
                   storyBoard.Completed -= handler;
                   onAnimationComplete();
               };

            storyBoard.Completed += handler;

            storyBoard.Begin();
        }
    }
}

